#include "Seqlist.h"

void SLPrint(SL *ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d  ", ps->a[i]);
	}
	printf(" %d", ps->size);
	printf("\n");
}

void SLInit(SL* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capicity = ps->size = 0;
}

void SLCheckCapaticy(SL *ps)
{
	assert(ps);

	if (ps->size == ps->capicity)
	{
		int newCapicity = ps->capicity == 0 ? 4 : 2 * (ps->capicity);
		SLdataType * tmp = (SLdataType *)realloc(ps->a, sizeof(SLdataType)*newCapicity);
		if (NULL == tmp)
		{
			perror("realloc:");
			exit(-1);
		}
		ps->a = tmp;
		ps->capicity = newCapicity;
	}
}

void SLPushBack(SL* ps, SLdataType x)
{
	assert(ps);

	SLCheckCapaticy(ps);

	ps->a[ps->size] = x;
	ps->size++;

	//SLInsert(ps, ps->size, x);
}

void SLPushFront(SL *ps, SLdataType x)
{
	//assert(ps);

	//SLCheckCapaticy(ps);

	//int end = ps->size - 1;
	//while (end >= 0)
	//{
	//	ps->a[end+1] = ps->a[end];
	//	end--;
	//}

	//ps->a[0] = x;
	//ps->size++;

	SLInsert(ps, 0, x);
}


void SLPopBack(SL *ps)
{
	assert(ps);

	assert(ps->size);

	ps->size--;
	//SLErase(ps, ps->size - 1);
}

void SLPopFront(SL *ps)
{
	assert(ps);

	assert(ps->size);
	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;

	//SLErase(ps, 0);
}


void SLDestory(SL *ps)
{
	assert(ps);

	if (ps->a != NULL)
	{
		free(ps->a);
		ps->a = NULL;
		ps->capicity = ps->size = 0;
	}
}

void SLInsert(SL* ps, int pos, SLdataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	SLCheckCapaticy(ps);

	int end = ps->size - 1;

	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}

	ps->a[pos] = x;
	ps->size++;

}


void SLErase(SL *ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	int begin = pos;

	while (begin < ps->size-1)
	{
		ps->a[begin] = ps->a[begin+1];
		begin++;
	}
	ps->size--;
}

int SLFind(SL *ps, SLdataType x)
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLModify(SL *ps, int pos, SLdataType x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	ps->a[pos] = x;
}